<script setup lang="ts">
import { useVModel } from '@vueuse/core'
import Decimal from 'decimal.js'
// type modelValue

const $props = defineProps({
    modelValue: {
        type: String,
        default: '0',
    },
    width: {
        type: Number,
        default: 200,
    },
    append: {
        type: String,
        default: '元',
    },
    precision: {
        type: Number,
        default: 2,
    },
})
const $emit = defineEmits(['update:modelValue'])
const inputValue = useVModel($props, 'modelValue', $emit)

/**
 * 转换输入值
 */
const handleInputBlur = (e: number | string) => {
    if (e === '') return
    const priceArr = String(new Decimal(e).absoluteValue()).split('.')
    if (priceArr.length > 1) {
        inputValue.value = `${priceArr[0]}.${priceArr[1].slice(0, $props.precision)}`
        return
    } else {
        inputValue.value = priceArr[0]
    }
}
</script>

<template>
    <el-input v-model="inputValue" type="number" :style="{ width: $props.width + 'px' }" @blur="handleInputBlur">
        <template #append>{{ $props.append }}</template>
    </el-input>
</template>

<style lang="scss" scoped></style>
